package server;
import utils.UserData;




/**
 * This listening service continuously listens to a port for incoming tagging requests from clients.
 * When a client asks for a tagging, a new TCP Connection is instantiated.
 */
public class DefaultListeningService extends Service {

	private Server server = Server.getSharedInstance();
	
	public DefaultListeningService() {
		super("Listening");
	}

	@Override
	public void run() {
		listen();
	}


	private void listen() {
		server.getFeedbackManager().printMessage("Listening...", false);
		
		while (true) {
			try {
				Connection incomingConn = new TCPConnection(server.getSingleProtocol().acceptConnection());
				UserData user = new UserData();
				//A user is identified by its IP address. Not used here, but it could be in some cases.
				user.putProperty("address", incomingConn.getSocket().getIPAddress().toString());
				user.putProperty("connectionThread", incomingConn);
				server.getUsersManager().addUser(user);
				incomingConn.startListening();
				server.getFeedbackManager().printMessage("Accepted connection request from "+
						incomingConn.getSocket().getIPAddress().toString(), false);
			} catch (Exception e) {
				e.printStackTrace();
				server.getFeedbackManager().printMessage("Error managing client connection request.", false);
				
			}
		}
	}


}
